package com.bawei.mall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.user.domain.*;
import com.bawei.mall.user.mapper.CompletionAddressMapper;
import com.bawei.mall.user.mapper.MallCusProductCarMapper;
import com.bawei.mall.user.mapper.MallProductOrderMapper;
import com.bawei.mall.user.mapper.UserMapper;
import com.bawei.mall.user.service.IMallProductOrderService;
import com.bawei.system.domain.model.LoginUser;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author：HaoYunde
 * @Package：com.bawei.mall.user.service.impl
 * @Project：mall_cloud
 * @name：IMallProductOrderServiceImpl
 * @Date：2024/7/9 11:19
 */
@Service
@Log4j2
public class MallProductOrderServiceImpl implements IMallProductOrderService {
    @Autowired
    private MallProductOrderMapper productOrderMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CompletionAddressMapper asyncAddressMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MallCusProductCarMapper carMapper;

    private static final String ACCESS_TOKEN="login_tokens:";


    /**
     * 订单确认
     * @param ids
     * @return
     */
    @Override
    public R<MallProductOrder> generateConfirmOrder(List<String> ids) {
        MallProductOrder mallProductOrder = new MallProductOrder();

        // 获取当前登录用户的ID
        Integer userId = getCurrentUserId();
        if (userId != null) {
            // 获取购物车中的商品信息
            List<MallProductEntity> entityList = carMapper.findListByUserIdAndProductIds(userId, ids);

            // 构建产品属性格式
            entityList.forEach(mallProductEntity -> {
                String sku = mallProductEntity.getProductAttr();
                String[] split = sku.split(",");
                List<Map<String, String>> type = new ArrayList<>();
                for (int i = 0; i < split.length; i++) {
                    Map<String, String> map = new HashMap<>();
                    map.put("key", String.valueOf(i + 1));
                    map.put("value", split[i]);
                    type.add(map);
                }
                mallProductEntity.setProductAttr(JSON.toJSONString(type));
            });

            // 设置购物车商品列表
            mallProductOrder.setCartPromotionItemList(new ArrayList<>(entityList));

            // 设置积分消费设置
            ConsumeSetting consumeSetting = new ConsumeSetting();
            consumeSetting.setId(1L);
            consumeSetting.setCouponStatus(1);
            consumeSetting.setDeductionPerAmount(100);
            consumeSetting.setMaxPercentPerOrder(50);
            consumeSetting.setUseUnit(100);
            mallProductOrder.setIntegrationConsumeSetting(consumeSetting);

            // 获取用户积分
            CusUser cusUser = userMapper.findIntegral(userId);
            if (cusUser != null) {
                // 设置会员积分
                mallProductOrder.setMemberIntegration(cusUser.getIntegral());

                // 获取用户地址
                List<MallProductAddress> mallProductAddress = asyncAddressMapper.getAddress(userId);
                mallProductOrder.setMemberReceiveAddressList(new ArrayList<>(mallProductAddress));

                // 计算总金额和折扣
                CalcAmount calcAmount = new CalcAmount();
                BigDecimal totalAmount = BigDecimal.ZERO;
                for (MallProductEntity mallProduct : entityList) {
                    BigDecimal price = mallProduct.getPrice();
                    totalAmount = totalAmount.add(price);
                }
                log.info("总金额：" + totalAmount);

                String discount = cusUser.getDiscount();
                if (discount != null && discount.endsWith("%")) {
                    BigDecimal discountRate = new BigDecimal(discount.substring(0, discount.length() - 1))
                            .divide(BigDecimal.valueOf(100));
                    BigDecimal discountAmount = totalAmount.multiply(discountRate);
                    log.info("折扣金额：" + discountAmount);
                    BigDecimal discountedTotalAmount = totalAmount.subtract(discountAmount);
                    log.info("折扣后的总金额：" + discountedTotalAmount);
                    calcAmount.setTotalAmount(totalAmount);
                    calcAmount.setPromotionAmount(discountedTotalAmount);
                    calcAmount.setPayAmount(totalAmount.subtract(discountedTotalAmount));
                } else {
                    // 没有折扣时的处理逻辑
                    calcAmount.setTotalAmount(totalAmount);
                    calcAmount.setPromotionAmount(BigDecimal.ZERO);
                    calcAmount.setPayAmount(totalAmount);
                }
                mallProductOrder.setCalcAmount(calcAmount);
            }

            return R.ok(mallProductOrder);
        } else {
            return R.fail("用户未登录");
        }
    }

    @Override
    public R<MallCusOrderInfo> generateOrder(MallCusOrderInfo orderInfo) {
        //获取当前登录用户的ID
        Integer userId = getCurrentUserId();
        orderInfo.setUserId(Long.valueOf(userId));
        productOrderMapper.generateOrder(orderInfo);
        //获取orderId
        orderInfo.setId(orderInfo.getId());
        return R.ok(orderInfo);
    }


    /**
     * 生成订单中间表
     * @param orderId,mallCusProductOrderMiddles
     */
    @Override
    public void generateOrderMiddle(Long orderId, List<MallCusProductOrderMiddle> mallCusProductOrderMiddles) {
        productOrderMapper.generateOrderMiddle(orderId,mallCusProductOrderMiddles);
    }



    /**
     * 订单列表
     * @param payStatus
     * @return
     */
    @Override
    public List<MallOrderList> list(Integer payStatus) {
        ArrayList<MallOrderList> mallOrderLists = new ArrayList<>();
        MallOrderList mallOrderList1 = new MallOrderList();
        List<MallOrderList> list=productOrderMapper.list(payStatus);
        List<Long> skuIds = new ArrayList<>();
        for (MallOrderList mallOrderList : list) {
            Long skuId = mallOrderList.getSkuId();
            skuIds.add(skuId);
        }
        ArrayList<MallProductEntity> mallProductEntities = new ArrayList<>();
        skuIds.forEach(skuId -> {
            MallProductEntity mallProductEntity = carMapper.findProductById(skuId);
            mallProductEntities.add(mallProductEntity);
        });
        for (MallProductEntity mallProductEntity : mallProductEntities) {
            String sku = mallProductEntity.getProductAttr();
            String[] split = sku.split(",");
            List<Map> type=new ArrayList<>();
            for (int i = 0; i < split.length; i++) {
                Map map = new HashMap<>();
                map.put("key",i+1);
                map.put("value",split[i]);
                type.add(map);
            }
            mallProductEntity.setProductAttr(JSON.toJSONString(type));
        }
        mallOrderList1.setOrderItemList(mallProductEntities);
        mallOrderLists.add(mallOrderList1);
        return mallOrderLists;
    }


    /**
     * 获取当前登录用户的ID
     * @return 用户ID
     */
    private Integer getCurrentUserId() {
        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String userKey = getTokenKey(key);
        String o = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser = JSON.parseObject(o, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        return cusUser.getUserId();
    }


    private String getTokenKey(String key) {
        return ACCESS_TOKEN + key;
    }
}
